# To change this template, choose Tools | Templates
# and open the template in the editor.

from common.mlib import MLib
from common.mmap import MMap
from pymongo import Connection

class MLibMapper:

    def __init__(self, mlib):        
        self.connection = Connection('localhost', 27017)
        self.db = self.connection['wodb']

    def _mlib_words_to_scheme(self, mlib):
        return      map(lambda w:
                    {
                        'word':
                        {
                            'name': w.get_name()
                        }
                    }, mlib.get_words())

    def _mlib_mmaps_to_scheme(self, mlib):
        return      map(lambda m:
                    {
                        'mmap':
                        {
                            'name': m.get_name(),
                            'words': map(lambda w:
                            {
                                'word':
                                {
                                    'name': w.get_name(),
                                    'associations': map(lambda a: a.get_name(), w.get_associations()),
                                    'translations': map(lambda t: t.get_name(), w.get_translations())
                                }
                            }, m.get_words())
                        }
                    }, mlib.get_maps())}

    def _scheme_to_mlib_mmaps(self, mlib):
        mmaps = self.db.mmaps
        for mmap in mmaps.find()
            mm = mlib.mmap_new(mmap['name'])
            for word in mmap['words'].find()
                w = mm.word_new_or_present(word['name'])
                for association in word['associations'].find()
                    w.update_associations(association)
                for translation in word['translations'].find()
                    w.update_translations(translation)
        return mlib

    def _scheme_to_mlib_words(self, mlib):
        words = self.db.words
        #map(lambda w: Word(w['name']), words.find())
        for word in words.find()
            mlib.add_word(word['name'])
        return mlib


    def load(self):
        print "MLibMapper load() method is invoked"
        return MLib()
        # Примерно так:
        return self._scheme_to_mlib_mmaps(self._scheme_to_mlib_words(MLib()))

    def save(self, mlib):
        print "MLibMapper save() method is invoked"
        return mlib
        # Примерно так
        self.db.words.insert(self._mlib_words_to_scheme(mlib))
        self.db.mmaps.insert(self._mlib_mmaps_to_scheme(mlib))
        return true
